<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\tool\account\Account;
use think\facade\Cache;
use think\Model;
use think\response\Json;
use think\model\relation\BelongsTo;

/**
 * @mixin \think\Model
 */
class Prize extends Base
{

    protected $name = 'prize';

    protected static array $_type = [
        1 => '谢谢惠顾',
        2 => '爱贝',
        3 => '链豆',
        4 => '爱豆',
        5 => 'VIP积分',
        6 => '积分',
        7 => '商品',
        8 => '抵扣券',
        9 => '话费券',
        10 => '电费券',
    ];

    public function getTypeTextAttr($value, $data): string
    {
        return isset(self::$_type[$data['type']]) ? self::$_type[$data['type']] : '谢谢惠顾';
    }

    public function getAwardsTextAttr($value, $data): string
    {
        if(!isset(self::$_type[$data['type']]) || $data['type'] == 1) return '谢谢惠顾';
        if($data['type'] == 7){
            return Product::where('id', $data['product_id'])->value('title') ?? '';
        }elseif(in_array($data['type'],[2,3,4,5,6])){
            return self::$_type[$data['type']].$data['amount'];
        }else{
            return '谢谢惠顾';
        }
    }

    public function types(): BelongsTo
    {
        return $this->belongsTo(PrizeType::class, 'type', 'id');
    }

    public static function getRandom($uid, $length = 8)
    {
        $list = parent::where('is_del', 0)->field('id,type,amount,odds,image,product_id')
            ->limit($length)->orderRaw('rand()')->select()->append(['awardsText']);
        $awards = [];
        foreach ($list as $k => $v) {
            $awards[] = [
                'id'         => $v->id,
                'type'       => $v->getData('type'),
                'awardsText' => $v->awardsText,
                'image'      => $v->image,
                'product_id' => $v->product_id
            ];
        }
        Cache::set('prizeAwards_' . $uid, $list);
        return $awards;
    }


    public static function luck($user): array
    {
        try {
            $prize_red_coin = Config::where('name', 'prize_red_coin')->value('value');
            if ($user->assets->red_coin < $prize_red_coin) {
                return ['code' => -1, 'msg' => '您没有抽奖机会了'];
            }
            $awards = Cache::get('prizeAwards_' . $user->id);
            if (!$awards) {
                return ['code' => -1, 'msg' => '哎呀，加载失败了，请尝试刷新页面后重试'];
            }

            $prize_arr = [];

            foreach ($awards as $k => $v) {
                $prize_arr[] = [
                    'id'    => $v['id'],
                    'prize' => $v['awardsText'],
                    'v'     => $v['odds'] * 100,
                    'type'  => $v->getData('type'),
                    'image' => $v['image'],
                    'product_id' => $v['product_id']
                ];

            }
            $arr = [];
            $p = [];
            foreach ($prize_arr as $key=>$val) {
                $arr[] = $val['v'];
                if($val['type'] == 7){
                    $p[] = [
                        'key' => $key,
                        'id'  => $val['id'],
                        'pid' => $val['product_id']
                    ];
                }
            }

            $awards = $prize_arr[self::get_rand($arr, $p)];
            unset($awards['v']);

            //查看奖项
            $info = self::with(['types'])->where('id', $awards['id'])->find()->toArray();//对象形式的$info->type有问题
            if ($info && $info['amount'] > 0) {
                if(in_array($info['type'], [2,3,4,5,6])){
                    $account = $info['types']['type'];
                    Account::getInstance()->basics($user->id, $account, $info['amount'], '中奖', '+')->createNormal($user->id);
                }else{
                    //其他费账户的情况
                }

            }
            Account::getInstance()->basics($user->id, 'red_coin', $prize_red_coin, '抽奖消耗积分', '-')->createNormal();

            $record = PrizeRecord::create([
                'uid'      => $user->id,
                'prize_id' => $awards['id'],
                'awards'   => $awards['prize'],
                'type'     => $awards['type']
            ]);

            $awards['times'] = Cache::get('prize_times', 0);
            $product = [];
            if($awards['type'] == 7 && $awards['product_id']){
                $productInfo = Product::with(['business'])->find($awards['product_id']);
                $spec = ProductSpecValue::where('pid', $awards['product_id'])->order('price', 'asc')->find();
                $specItem = SpecItem::whereIn('id', str_replace('-', ',', $spec->sku_id))->column('name');
                $product = [
                    [
                        'prize_record_id' => $record->id,
                        'business_id' => $productInfo->business_id,
                        'business_remarks' => '抽奖所得',
                        'business_title' => $productInfo->business->title,
                        'business_customer_tel' => $productInfo->business->customer_tel,
                        'children' => [
                            [
                                'pid' => $awards['product_id'],
                                'spec_value_id' => $spec->id,
                                'sku_name' => implode('/', $specItem),
                                'cate_1' => $productInfo->cate_1,
                                'num' => 1,
                                'business_id' => $productInfo->business_id,
                                'discount_id' => 0,
                                'product_title' => $productInfo->title,
                                'product_cover' => $productInfo->cover,
                                'product_describe' => $productInfo->describe
                            ]
                        ]
                    ]
                ];

                $record->status = 0;
                $record->product_id = $awards['product_id'];
                $record->product_info = json_encode($product, JSON_UNESCAPED_UNICODE);
                $record->save();
            }
            $awards['product'] = $product;
            return ['code' => 1, 'msg' => 'success', 'data' => $awards];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function get_rand($proArr, $product)
    {
        $result = '';
        $prize_times = Cache::get('prize_times', 0);

        $hasProduct = false;
        if($product){
            foreach ($product as $p){
                $prize_times_p = Cache::get('prize_times_pid_'.$p['pid'], 0);

                if($count = self::where('id', $p['id'])->value('count')){
                    //var_dump(($prize_times+1).'|'.$count);
                    /*if(($prize_times_p + 1) % $count == 0){//倍数
                        //var_dump('抽中商品了~');
                        $hasProduct = true;
                        $result = $p['key'];
                        break;
                    }*/

                    if(($prize_times_p + 1) == $count){
                        $hasProduct = true;
                        $result = $p['key'];
                        break;
                    }
                }
            }
        }

        if(!$hasProduct){
            $proSum = (int)array_sum($proArr);
            foreach ($proArr as $key => $proCur) {
                $randNum = mt_rand(1, $proSum);
                if ($randNum <= $proCur) {
                    $result = $key;
                    break;
                } else {
                    $proSum -= (int)$proCur;
                }
            }
            unset ($proArr);
        }
        $prize_times ++;
        Cache::set('prize_times', $prize_times);

        $pids = self::where('product_id', '>', 0)->where('is_del', 0)->column('product_id');
        foreach ($pids as $pid){
            $p_times = Cache::get('prize_times_pid_'.$pid, 0);
            $p_times ++ ;
            Cache::set('prize_times_pid_'.$pid, $p_times);
        }

        return $result;
    }

    public static function _save($param, $admin): array
    {
        parent::startTrans();
        try {
            if (isset($param['id']) && $param['id']) {
                $otherOdds = self::where('id', '<>', 1)->where('id', '<>', $param['id'])->sum('odds');
                $odds = $otherOdds + $param['odds']/100;
                if($odds >= 1){
                    return ['code'=>-1, 'msg'=>'中奖几率设置已超限'];
                }
                $param['odds'] = $param['odds']/100;

                $info = parent::find($param['id']);
                if($info->getData('type') != $param['type'] || $info->getData('amount') != $param['amount'] || $info->getData('odds') != $param['odds'] || $info->getData('product_id') != $param['product_id'] || $info->getData('count') != $param['count']){

                    $t = PrizeType::where('is_del', 0)->column('title', 'id');
                    $log = [
                        'admin_id' => $admin['id'],
                        'admin_name' => $admin['admin_name'],
                    ];
                    if($info->getData('type') != $param['type']){
                        $log['content'] = "抽奖设置ID【".$info->id."】由类型【".$t[$info->id]."】修改为【".$t[$param['type']]."】；";
                        PrizeLog::create($log);
                    }else{
                        if($info->getData('type') == 7){
                            $p_title = Product::where('id', $info->product_id)->value('title');
                            $q_title = Product::where('id', $param['product_id'])->value('title');
                            $log['content'] = "抽奖设置ID【".$info->id."】由商品【".$p_title."[ID:".$info->product_id."]，中奖次数：".$info->getData('count')."】修改为"."【".$q_title."[ID:".$param['product_id']."]中奖次数：".$param['count']."】";
                        }else{
                            $log['content'] = "抽奖设置ID【".$info->id."】类型【".$t[$info->id]."】由原金额【".$info->amount."】，原中奖几率【".($info->odds * 100)."%】修改为  金额【".$param['amount']."】，中奖几率【".($param['odds'] * 100)."%】";
                        }
                        PrizeLog::create($log);
                    }
                }

                $model = parent::update($param);
                parent::where('id', 1)->save(['odds'=>1-$odds]);
                $info = parent::find($param['id']);
                if($info->product_id){
                    Cache::set('prize_times_pid_'.$info->product_id, 0);
                }

                $model->operation = 'save';
            } else {
                $model = parent::create($param);
                $model->operation = 'create';
            }
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

}
